package com.zy.fee.roadpark.receiver;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Vibrator;
import android.support.v4.app.NotificationCompat;
import android.util.Log;


import com.zy.fee.roadpark.R;
import com.zy.fee.roadpark.activity.MainActivity;
import com.zy.fee.roadpark.activity.np.LeaveApplyActivity;

import cn.jpush.android.api.CmdMessage;
import cn.jpush.android.api.CustomMessage;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.NotificationMessage;
import cn.jpush.android.service.JPushMessageReceiver;

public class PushMessageReceiver extends JPushMessageReceiver {
    private static final String TAG = "PushMessageReceiver";

    @Override public void onMessage(Context context, CustomMessage customMessage) {
        Log.e(TAG, "[onMessage] " + customMessage);
        Intent intent = new Intent("com.jiguang.demo.message");
        intent.putExtra("msg", customMessage.message);
        context.sendBroadcast(intent);

        processCustomMessage(context, customMessage);
    }

    @Override public void onNotifyMessageOpened(Context context, NotificationMessage message) {
        Log.e(TAG, "[onNotifyMessageOpened] " + message);
        try {
            //打开自定义的Activity
            Intent i = new Intent(context, LeaveApplyActivity.class);
            Bundle bundle = new Bundle();
            bundle.putString(JPushInterface.EXTRA_NOTIFICATION_TITLE, message.notificationTitle);
            bundle.putString(JPushInterface.EXTRA_ALERT, message.notificationContent);
            i.putExtras(bundle);
            i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
            context.startActivity(i);
        } catch (Throwable throwable) {

        }
    }

    @Override public void onMultiActionClicked(Context context, Intent intent) {
        Log.e(TAG, "[onMultiActionClicked] 用户点击了通知栏按钮");
        String nActionExtra = intent.getExtras().getString(JPushInterface.EXTRA_NOTIFICATION_ACTION_EXTRA);

        //开发者根据不同 Action 携带的 extra 字段来分配不同的动作。
        if (nActionExtra == null) {
            Log.d(TAG, "ACTION_NOTIFICATION_CLICK_ACTION nActionExtra is null");
            return;
        }
        if (nActionExtra.equals("my_extra1")) {
            Log.e(TAG, "[onMultiActionClicked] 用户点击通知栏按钮一");
        } else if (nActionExtra.equals("my_extra2")) {
            Log.e(TAG, "[onMultiActionClicked] 用户点击通知栏按钮二");
        } else if (nActionExtra.equals("my_extra3")) {
            Log.e(TAG, "[onMultiActionClicked] 用户点击通知栏按钮三");
        } else {
            Log.e(TAG, "[onMultiActionClicked] 用户点击通知栏按钮未定义");
        }
    }

    @Override public void onNotifyMessageArrived(Context context, NotificationMessage message) {
        Log.e(TAG, "[onNotifyMessageArrived] " + message);
    }

    @Override public void onNotifyMessageDismiss(Context context, NotificationMessage message) {
        Log.e(TAG, "[onNotifyMessageDismiss] " + message);
    }

    @Override public void onRegister(Context context, String registrationId) {
        Log.e(TAG, "[onRegister] " + registrationId);
        Intent intent = new Intent("com.jiguang.demo.register");
        context.sendBroadcast(intent);
    }

    @Override public void onConnected(Context context, boolean isConnected) {
        Log.e(TAG, "[onConnected] " + isConnected);
    }

    @Override public void onCommandResult(Context context, CmdMessage cmdMessage) {
        Log.e(TAG, "[onCommandResult] " + cmdMessage);
    }

    //@Override
    //public void onTagOperatorResult(Context context, JPushMessage jPushMessage) {
    //    TagAliasOperatorHelper.getInstance().onTagOperatorResult(context,jPushMessage);
    //    super.onTagOperatorResult(context, jPushMessage);
    //}
    //
    //@Override
    //public void onCheckTagOperatorResult(Context context, JPushMessage jPushMessage) {
    //    TagAliasOperatorHelper.getInstance().onCheckTagOperatorResult(context,jPushMessage);
    //    super.onCheckTagOperatorResult(context, jPushMessage);
    //}
    //
    //@Override
    //public void onAliasOperatorResult(Context context, JPushMessage jPushMessage) {
    //    TagAliasOperatorHelper.getInstance().onAliasOperatorResult(context,jPushMessage);
    //    super.onAliasOperatorResult(context, jPushMessage);
    //}
    //
    //@Override
    //public void onMobileNumberOperatorResult(Context context, JPushMessage jPushMessage) {
    //    TagAliasOperatorHelper.getInstance().onMobileNumberOperatorResult(context,jPushMessage);
    //    super.onMobileNumberOperatorResult(context, jPushMessage);
    //}

    @Override public void onNotificationSettingsCheck(Context context, boolean isOn, int source) {
        super.onNotificationSettingsCheck(context, isOn, source);
        Log.e(TAG, "[onNotificationSettingsCheck] isOn:" + isOn + ",source:" + source);
    }

    private void processCustomMessage(Context context, CustomMessage customMessage) {
        try {
            //JSONObject message = new JSONObject(customMessage.message);
            //String Text = "你有一条新消息";
            //if(message.has("Text")){
            //    Text = message.getString("Text");
            //}
            showNotification(context, customMessage.message);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static int notificationID = 1;
    private void showNotification(Context mContext, String content) {
        //自定义打开的界面
        Intent resultIntent = new Intent(mContext, MainActivity.class);
        resultIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        PendingIntent contentIntent =
            PendingIntent.getActivity(mContext, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);

        NotificationManager notificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
        Notification notification = null;

        // 适配8.0及以上 创建渠道
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            String id = "channel_01";
            String name = "渠道01";
            NotificationChannel mChannel = new NotificationChannel(id, name, NotificationManager.IMPORTANCE_LOW);
            mChannel.enableVibration(true);  // 设置通知出现时的震动（如果 android 设备支持的话）
            notificationManager.createNotificationChannel(mChannel);
            notification = new Notification.Builder(mContext)
                .setChannelId(id)
                .setContentTitle("路内车位管理")
                .setContentText(content)
                .setSmallIcon(R.mipmap.icon_small_icon)
                .setColor(Color.parseColor("#527FDB"))
                //.setLargeIcon(BitmapFactory.decodeResource(mContext.getResources(), R.mipmap.icon_launcher))
                .setWhen(System.currentTimeMillis())
                .setAutoCancel(true)//点击后自动消失
                .setShowWhen(true)
                .setDefaults(Notification.DEFAULT_VIBRATE | Notification.DEFAULT_SOUND)
                .setContentIntent(contentIntent)
                .setFullScreenIntent(contentIntent,true)
                .build();
        } else {
            NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(mContext)
                .setContentTitle("路内车位管理")
                .setContentText(content)
                .setSmallIcon(R.mipmap.icon_small_icon)
                .setColor(Color.parseColor("#527FDB"))
                .setOngoing(true)
                .setAutoCancel(true)//点击后自动消失
                .setWhen(System.currentTimeMillis())
                .setDefaults(Notification.DEFAULT_VIBRATE | Notification.DEFAULT_SOUND)
                .setContentIntent(contentIntent);
            //.setChannel(id);//无效
            notification = notificationBuilder.build();
        }

        notificationManager.notify(notificationID, notification);
        notificationID++;

        // pda通知声音和震动无效，采用此方式
        playNotificationRing(mContext);
        playNotificationVibrate(mContext);
    }

    /**
     * 播放通知声音
     */
    private void playNotificationRing(Context context) {
        Uri uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        Ringtone rt = RingtoneManager.getRingtone(context, uri);
        rt.play();
    }

    /**
     * 手机震动一下
     */
    private void playNotificationVibrate(Context context) {
        Vibrator vibrator = (Vibrator) context.getSystemService(Service.VIBRATOR_SERVICE);
        long[] vibrationPattern = new long[]{0, 180, 80, 120};
        // 第一个参数为开关开关的时间，第二个参数是重复次数，振动需要添加权限
        vibrator.vibrate(vibrationPattern, -1);
    }
}
